from django import forms
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from apps.blog.models import Article


class ArticleForm(forms.Form):
    title = forms.CharField(widget=forms.TextInput(attrs={
        'placeholder': _("Title"),
        'class': 'span6'
    }))
    content = forms.CharField(widget=forms.Textarea)
    slug = forms.SlugField(required=False, widget=forms.TextInput(attrs={
        'placeholder': _(
            "If you leave slug empty, it will be prepopulated with title."),
        'class': 'span5'
    }))
    is_published = forms.BooleanField(required=False)

    def clean_slug(self):
        slug = self.cleaned_data.get('slug')

        if not slug:
            title = self.cleaned_data.get('title')
            slug = str(slugify(title))

        # check slug validation.
        if slug and Article.all().filter('slug', slug).count():
            raise forms.ValidationError(_("Slug should be unique."))

        return slug


class ArticleEditForm(ArticleForm):
    def clean_slug(self):
        slug = self.cleaned_data.get('slug')

        if not slug:
            raise forms.ValidationError(_("Slug shouldn't be empty."))

        return slug
